package com.zh.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.zh.dao.UserDao;
import com.zh.model.User;
import com.zh.utils.JdbcUtil;

@Repository
public class UserDaoImpl implements UserDao{
	
//	public UserDaoImpl(String names) {
//		
//	}

	
	@Override
	public void add(User user) {
		
		
//		insert into user(name,password) values('你好','123456')
//		String a = "'你好'" + ",'123456'";--> 
		String sql = "insert into user(name ,password ,phone,idcard,addr,status) "
				+ " values ('"+ user.getName()+"','"+ user.getPassword()+"',"
						+ "'" + user.getPhone() +"','"+ user.getIdcard()+"',"
								+ "'"+ user.getAddr()+"',"+ user.getStatus() +")";
		System.out.println(sql);
		JdbcUtil.excute(sql);
	}

	@Override
	public void mod(User user) {
//		update user set name = '' and password = '' ,
		String sql = "update user set ";
		if(user.getName() != null && user.getName() !="" ) {
			sql += " name = '" + user.getName() +"'"; 
		}
		if(user.getPassword() != null && user.getPassword() != "") {
			sql += ",  password = '" + user.getPassword() +"'";
		}
		sql += " where id = " + user.getId();
		System.out.println(sql);
		JdbcUtil.excute(sql);
	}

	@Override
	public void del(int id) {
		String sql = "delete from user where id = " +id;
		JdbcUtil.excute(sql);
	}

	@Override
	public List<User> query(User user) {
		List<User> userResult = new ArrayList<>();
//		select * from user where 1=1 and password = '',
		String sql = "select * from user  where 1 =1 ";
		if(user.getName() != null && user.getName() != "") {
			sql += " and name = '"+ user.getName() +"'";
		}
		if(user.getPassword() != null && user.getPassword() !="") {
			sql += " and password = '" + user.getPassword() +"'";
		}
		List result = JdbcUtil.excuteQuery(sql);
		//把数据库结果集转变为对象
		for(int i = 0 ; i< result.size() ; i++) {
			User tuser = new User();
			Map<String, Object> map = (Map<String, Object>) result.get(i);
		    try {
		    	//把map对象转变为bean
				BeanUtils.populate(tuser, map);
			} catch(Exception e) {
				e.printStackTrace();
			} 
			userResult.add(tuser);
		}
		return userResult;
		
	}

	@Override
	public int login(User user) {
		String sql = "select * from user  where name = '" + user.getName()+"'"
				+ " and password = '" + user.getPassword() +"'";
		List result = JdbcUtil.excuteQuery(sql);
		return result.size();
	}

}
